package com.teamclub.app.sservices

import java.awt.image.BufferedImage
import java.util.Date

import com.google.code.kaptcha.Producer
import com.teamclub.domain.system.AppCaptcha
import com.teamclub.util.exception.TcException
import com.teamclub.util.utils.DateUtils
import io.ebean.{Ebean, EbeanServer}
import org.apache.commons.lang3.StringUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class CaptchaService {
  @Autowired
  var ebeanServer: EbeanServer = _
  @Autowired
  var producer: Producer = _

  def getCaptcha(uuid: String): BufferedImage = {
    if (StringUtils.isBlank(uuid)) throw new TcException("uuid不能为空")
    //生成文字验证码
    val code = producer.createText
    val captchaEntity = new AppCaptcha
    captchaEntity.setUuid(uuid)
    captchaEntity.setCode(code)
    //5分钟后过期
    captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date, 5))
    captchaEntity.save()
    producer.createImage(code)
  }

  def validate(uuid: String, code: String): Boolean = {
    val appCpatcha = Option.apply(ebeanServer.find(classOf[AppCaptcha]).where().eq("uuid", uuid).findOne())
    appCpatcha match {
      case Some(v) => {
        v.getCode.equalsIgnoreCase(code) && v.getExpireTime.getTime >= System.currentTimeMillis()
      }
      case None => false
    }
  }
}
